﻿using Domain.Entities.Back_End_Return_Result_Entities;
using Domain.Entities.Front_End_Parm_Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ReLifeProject.Controllers.Post
{
    [ApiController]
    [AllowAnonymous]
    [Route("[controller]")]
    public class Post_accountLogin_vue_Controller : Controller
    { 
        [HttpPost("/PostaccountLogin")]
        public async Task<accountLogin_vue_Result> PostaccountLogin([FromBody] accountLogin_vue acount)
        {
            Console.WriteLine(acount.accountName);
            Console.WriteLine(acount.accountPassWord);
            //从数据库验证用户名，密码
            //验证通过 否则 返回Unauthorized

            //创建claim
            var authClaims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub,acount.accountName),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
            };
            IdentityModelEventSource.ShowPII = true;
            //签名秘钥 可以放到json文件中
            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey"));

            var token = new JwtSecurityToken(
                   issuer: "http://localhost:13164",
                   audience: "http://localhost:13164",
                   expires: DateTime.Now.AddHours(2),
                   claims: authClaims,
                   signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                   );

            await Task.Run(() =>
            {
                Console.WriteLine(token);
            });

            //返回token和过期时间
            return new accountLogin_vue_Result
            {
                Duration = 7200,
                Expiration = token.ValidTo,
                IsSuccess = true,
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            };
        }
    }
}
